package app.web.controller;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.base.Strings;

import app.model.Demo;
import keter.framework.web.util.MediaType;
import keter.web.controller.base.KeterBaseController;


/**
 * <p>Class       : app.controller.IndexLoginController
 * <p>Descdription: 首页和登录控制逻辑的统一处理
 *
 * @author  gulixing@msn.com
 * @version 1.0.0
 */
@RestController
@RequestMapping("app/demo")//注意："path"和"path/"是两个不同的映射
public class DemoController extends KeterBaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(DemoController.class);
    
    @GetMapping(value=Routes.Index)
    public ModelAndView index(Model model) throws Exception {        
        logger.info("访问/app/demo，跳转到/app/demo/demo_index.jsp 页面");
        //getDefaultPath只适用于包含@RequestMapping注解的类
        return new ModelAndView(getDefaultPath()+"index");
//        return new ModelAndView("yourapp/demo/demo_index");
    }
    
    @GetMapping(value=Routes.Get, produces=MediaType.APPLICATION_JSON_UTF_8)
    public String getOne(@PathVariable Long id) throws Exception {        
    	return toJson(Demo.dao.findById(id));
    }
    
    @GetMapping(value=Routes.GetAll, produces=MediaType.APPLICATION_JSON_UTF_8)
    public String getAll() throws Exception {        
    	return toJson(Demo.dao.findAll());
    }  
    
    @GetMapping(value=Routes.GetPaged)
    public String getPaged(@PathVariable int pageNumber,@PathVariable int pageSize) throws Exception {        
    	return toJson(Demo.dao.paginate(pageNumber, pageSize));
    }
    
    @GetMapping(value=Routes.Add)
    public ModelAndView add() throws Exception {        
        logger.info("访问/yourapp/demo/add，跳转到/yourapp/demo/demo_add.jsp 页面");
//        return new ModelAndView(getDefaultPath()+"add");
        return new ModelAndView("app/demo/demo_add");
    }
    
    //,HttpServletResponse response
    @RequestMapping(value=Routes.Add, method = RequestMethod.POST)
    public String update(HttpServletRequest request) throws Exception {        
        Demo u = new Demo();
        //自动为属性赋值
        setModelAttrFromRequest(u, request);
        //生成创建时间:此处可以完成一些不通过前台传值的字段
        if(Strings.isNullOrEmpty((String) u.get("create_date"))){
            u.set("create_date",new Date());
        }
        u.save();
        return success();
    }
}
